/** 
 * Copyright (C) 2018 Jeebiz (http://jeebiz.net).
 * All Rights Reserved. 
 */
package net.jeebiz.cloud.extras.core.setup.fegin;

import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import feign.RequestInterceptor;
import feign.RequestTemplate;
import net.jeebiz.cloud.api.utils.StringUtils;

public class FeignRequestInterceptor implements RequestInterceptor {

	/**
	 * admin 账户生成的token
	 */
    public static final String TOKEN_ADMIN = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiIsInppcCI6IkRFRiJ9.eNqMkD1uwzAMhe-isTACUo7kny117XtQkQywcezAsuEEQcd2breunbp17ND7FO4xKgM-QDi9j3wkSF4FtzwwNSKvqfEuEn3XOC9yQfbIrYgENUwL_30_zz-f89fH_Pry-_YeKifXH5fKXdCjd_2-sy6gXJFtgPR-l1RFkRRZvC10-VCCAoCkAgTQZZWt3oO7rJ2PAwdlaky1ccYi1ErKVBpN0oKxMap6SyoY_Whum0_jjYuwX66ZQmwObTdNdNnslw8wDSJHpWMJCgEj4c6nNZGhAnz6BwAA__8.GoSPlpX6rsrs29o4gADTqR0jQ1ZmuCSttTdIcyZnpd8";
    public static final String TOKEN_HEADER = "X-Authorization";
    
    @Override
    public void apply(RequestTemplate template) {
    	HttpServletRequest request = getHttpServletRequest();
    	if(request != null) {
    		String s = getHeaders(request).get(TOKEN_HEADER);
	        if (StringUtils.isEmpty(s)){
	            s = TOKEN_ADMIN;
	        }
	        template.header(TOKEN_HEADER, s);
    	} else {
    		 template.header(TOKEN_HEADER, TOKEN_ADMIN);
		}
    }

    private HttpServletRequest getHttpServletRequest() {
        try {
            return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        } catch (Exception e) {
            return null;
        }
    }

    private Map<String, String> getHeaders(HttpServletRequest request) {
        Map<String, String> map = new LinkedHashMap<>();
        Enumeration<String> enumeration = request.getHeaderNames();
        while (enumeration.hasMoreElements()) {
            String key = enumeration.nextElement();
            String value = request.getHeader(key);
            map.put(key, value);
        }
        return map;
    }
}
